﻿using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.HZJLYModel;
using DongFangGuoKai.WMSPlatform.Domain.LIMSModels;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail.DTO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Transactions;

namespace DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail
{
    public partial class TReceivingOrderDetailService: ITReceivingOrderDetailService
    {
        protected readonly static object _lockObj = new object();
        static IConfiguration _config;
        static TReceivingOrderDetailService()
        {
            _config = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource { Path = "/system.json", ReloadOnChange = true })
                .Build();
             
        }

        /// <summary>
        /// 新组垛
        /// </summary>
        /// <param name="errMsg"></param>
        /// <param name="stackingStorageDTO"></param>
        /// <returns></returns>
        public bool NewStackingStorage(out string errMsg, StackingStorageDTO stackingStorageDTO)
        {
            errMsg = string.Empty;
            if (stackingStorageDTO.userId == 0 || stackingStorageDTO.sampleCode == null)
            {
                errMsg = "参数有误";
                return false;
            }
            //查询委托单样品信息
             var receivingbilldteail = receivingbillDteailrepost.Get(s => s.MaterialCode == stackingStorageDTO.sampleCode && s.PositionType == 1);
            if (receivingbilldteail is null)
            {
                errMsg = "未查出委托单或者样品不属于此库区";
                return false;
            }
            using var trans = new TransactionScope();
            try
            {
                List<SampleCirculationModel> sampleCirculationModels = new List<SampleCirculationModel>();
                TPallet pall;
                SpreadWalls spread = null; //如果大件组垛的话不用赋值

                //查看委托单是否已经组垛
                var stackingstorage = tStackingStorageServicerepost.Get(s => s.OrderNo == receivingbilldteail.BillNo && s.Status == 1 && s.SeqNum != null && s.NWall != null && s.TagIndex != null);
                //没有组垛过就去对应表里找一个电子标签地址点亮
                if (stackingstorage is null)
                {
                    //根据设备序列号查出可以用的电子标签地址 排序条件墙号和地址
                    var spreadlist = spreadwallsrepost.GetList(s => s.SwitchState == 0 && s.SeqNum == "389222871").OrderByDescending(s=>s.NWall).OrderByDescending(s=>s.TagIndex).ToList();
                    if (spreadlist is null || spreadlist.Count <= 0)
                    {
                        errMsg = "没有可用的地址";
                        return false;
                    }
                    bool isspread = false;
                    foreach (var item in spreadlist)
                    {
                        var cellobj = cellrepost.Get(c=>c.Code == item.CellCode);
                        if (cellobj is null)
                        {
                            errMsg = "未查出电子标签仓位";
                            return false;
                        }
                        if (cellobj.BusinessType != 0 || cellobj.FullStatus == 1 || cellobj.IsLock == true || cellobj.Status == 2)
                        {
                            continue;
                        }
                        //查看地址对应的仓位是否具有托盘 如果没有就寻找下一个 
                        var pallcell = palletrepost.Get(p => p.LocationCode == item.CellCode && p.Status == 1);
                        if (pallcell is not null)
                        {
                            spread = item;
                            isspread = true;
                            //分到的分播墙的仓位需要改一下当前业务
                            cellobj.BusinessType = EmBusinessType.In;
                            cellobj.IsLock = true;
                            cellobj.Status = 2;
                            if (!cellrepost.Update(cellobj))
                            {
                                errMsg = "分播墙仓位状态修改失败，" + cellobj.Name;
                                trans.Dispose();
                                return false;
                            }
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (!isspread)
                    {
                        errMsg = "没有可用的地址";
                        return false;
                    }

                }
                else
                {
                        
                    spread = spreadwallsrepost.Get(s => s.TagIndex == stackingstorage.TagIndex && s.NWall == stackingstorage.NWall && s.SeqNum == stackingstorage.SeqNum);

                }
                var usercolor = usercolorrepost.Get(u => u.UserId == stackingStorageDTO.userId);
                if (usercolor is null)
                {
                    errMsg = "请先选择点亮的颜色";
                    return false;
                }
                SuccessTagRequest successTagRequest = new SuccessTagRequest();
                successTagRequest.nWall = spread.NWall;
                successTagRequest.seqNum = spread.SeqNum;
                successTagRequest.tagList = new List<Tag>()
                {
                    new Tag() { showColor = usercolor.ShowColor, showData = spread.TagIndex, tagIndex = spread.TagIndex },
                };
               
                //小件的话可以通过分播墙的那储位找出对应的箱号
                pall = palletrepost.Get(p => p.LocationCode == spread.CellCode && p.Status == 1);
                if (pall is null)
                {
                    errMsg = "未查询到箱号";
                    trans.Dispose();
                    return false;
                }

                //如果样品已在在托盘或箱号上组垛过就只返回
                var data = tStackingStorageServicerepost.Get(s => s.Status == 1
                            && s.MaterialCode == stackingStorageDTO.sampleCode
                            && s.PalletBarcode == pall.PalletBarcode
                            && s.OrderNo == receivingbilldteail.BillNo);
                if (data is not null)
                {
                    errMsg = "保存成功,箱号为：" + data.PalletBarcode;
                    trans.Complete();
                    return true;
                }
                //根据委托单去查看是否有入库单号
                var receorder = receivingOrderDetailrepost.Get(r => r.ReceivingBillId == receivingbilldteail.BillId);
                TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                if (receorder is null)
                {
                    receivingOrder.OrderSn = "TW" + GetInOrderBarCode();
                }
                else
                {
                    receivingOrder.OrderSn = receorder.OrderSn;
                }

                receivingOrder.BillType = 1;
                receivingOrder.MaterialId = receivingbilldteail.MaterialId;
                receivingOrder.MaterialCode = receivingbilldteail.MaterialCode;
                receivingOrder.MaterialName = receivingbilldteail.MaterialName;
                receivingOrder.Status = 3;
                receivingOrder.ReceivingBillId = receivingbilldteail.BillId;
                receivingOrder.ReceivingBillDetailId = receivingbilldteail.Id;
                receivingOrder.CreateDate = DateTime.Now;
                if (receivingOrderDetailrepost.Insert(receivingOrder) is null)
                {
                    trans.Dispose();
                    errMsg = "添加入库单失败";
                    return false;
                }
                //查看箱号是否组垛过 没有组垛过就要从新生成一个组垛的号代表新的一次
                var stacking = tStackingStorageServicerepost.Get(s =>
                s.OrderNo == receivingbilldteail.BillNo
                && s.PalletBarcode == pall.PalletBarcode
                && s.Status == 1
                );
                TStackingStorage stackingStorage = new TStackingStorage();
                if (stacking is null)
                {
                    stackingStorage.Code = "ST" + GetInOrderBarCode();
                }
                else
                {
                    stackingStorage.Code = stacking.Code;
                }

                stackingStorage.RelatedOrderDetailId = receivingOrder.Id;
                stackingStorage.MaterialId = receivingbilldteail.MaterialId;
                stackingStorage.MaterialCode = receivingbilldteail.MaterialCode;
                stackingStorage.CreateDate = DateTime.Now;
                stackingStorage.OrderNo = receivingbilldteail.BillNo;
                stackingStorage.MaterialName = receivingbilldteail.MaterialName;
                stackingStorage.Status = 1;
                stackingStorage.PalletBarcode = pall.PalletBarcode; //箱号或托盘号
                if (receivingbilldteail.PositionType == 1)
                {
                    stackingStorage.TagIndex = spread.TagIndex;
                    stackingStorage.SeqNum = spread.SeqNum;
                    stackingStorage.NWall = spread.NWall;
                }
                if (tStackingStorageServicerepost.Insert(stackingStorage) is null)
                {
                    trans.Dispose();
                    errMsg = "组垛失败";
                    return false;
                }

                //查看是否需要自动满箱 自动满箱：委托单的物料都组垛过了就自动满箱了
                var stackingList = tStackingStorageServicerepost.GetList(s =>
                s.OrderNo == receivingbilldteail.BillNo
                && s.PalletBarcode == pall.PalletBarcode
                && s.Status == 1
                );
                //只查看货架和大件区 查询委托单样品信息
                var receivingList = receivingbillDteailrepost.GetList(r => r.BillNo == receivingbilldteail.BillNo && r.PositionType == 1);
                if (receivingList.Count == stackingList.Count())
                {
                    var IsBright = electronicTSpreadWallsags.successTagResults(successTagRequest, out errMsg);
                    if (!IsBright)
                    {
                        errMsg = "点亮电子标签地址失败：" + errMsg;
                        trans.Dispose();
                        return false;
                    }
                    //自动满箱
                    var IsOk = FullBoxLarge(stackingStorage.PalletBarcode,out string cellName, out errMsg);
                    if (IsOk)
                    {
                        trans.Complete();
                        errMsg = "委托单已完成,已自动满箱上架:" + cellName;
                        return true;
                    }
                    trans.Dispose();
                    errMsg = "组垛失败：" + errMsg;
                    return false;
                }
               
                sampleCirculationModels.Add(new SampleCirculationModel()
                {
                    nodeName = "业务部待上架区",
                    sampleId = receivingbilldteail.MaterialId.GetValueOrDefault(),
                    staffName = "" //后面需要写接件人的名称
                });
                var limsres = limsService.SampleCirculation(sampleCirculationModels);
                if (limsres.code != 200)
                {
                    receivingservicelogger.LogError("回传lims样品上架信息失败 ,入参：" + sampleCirculationModels.ToJson() + "出参" + limsres.ToJson());
                    errMsg = "回传lims节点失败：" + limsres.msg;
                    trans.Dispose();
                    return false;
                }
                receivingservicelogger.LogInformation("回传lims样品上架信息成功 ,入参：" + sampleCirculationModels.ToJson() + "出参" + limsres.ToJson());

                //调用电子标签点亮地址
                var IsLis = electronicTSpreadWallsags.successTagResults(successTagRequest, out errMsg);
                if (!IsLis)
                {
                    errMsg = "点亮电子标签地址失败：" + errMsg;
                    trans.Dispose();
                    return false;
                }
                trans.Complete();
                errMsg = "保存成功,箱号为：" + pall.PalletBarcode;
                return true;
            }
            catch (Exception ex)
            {
                trans.Dispose();
                errMsg = ex.Message;
                return false;
                throw;
            }
            
        }

        /// <summary>
        /// 手动满箱
        /// </summary>
        /// <param name="palletCode"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool FullBox(string palletCode,out string errMsg)
        {
            errMsg = string.Empty;
            string cellName = string.Empty;
            var stackingStorages = tStackingStorageServicerepost.GetList(s=>s.Status == 1 && s.PalletBarcode == palletCode);
            if (stackingStorages.Count <= 0 || stackingStorages is null)
            {
                errMsg = "未查询到组垛信息";
                return false;
            }
            using var trans = new TransactionScope();
            try
            {
                foreach (var storage in stackingStorages)
                {
                    var orderdetail = receivingOrderDetailrepost.Get(r => r.Id == storage.RelatedOrderDetailId);
                    if (orderdetail is null)
                    {
                        errMsg = "未查询到组垛信息";
                        trans.Dispose();
                        return false;
                    }
                    PalletBindMaterialModel palletBindMaterialModel = new PalletBindMaterialModel()
                    {
                        PalletBarcode = storage.PalletBarcode,
                        StackingStorageId = storage.Id,
                        MaterialPackageBindModel = new MaterialPackageBindModel()
                        {
                            OrderDetailId = orderdetail.Id,
                            MaterialCode = storage.MaterialCode,

                        }
                    };
                    var isok = NewExecCreateMaterialsInstruct(out errMsg,out cellName, orderdetail, palletBindMaterialModel);
                    if (!isok)
                    {
                        errMsg = "开始入库失败：" + errMsg;
                        trans.Dispose();
                        return false;
                    }
                }

                var instruct = instructrepost.Get(i => i.StackingStorageCode == stackingStorages[0].Code);
                if (instruct is null)
                {
                    errMsg = "未查询到指令：" + errMsg;
                    trans.Dispose();
                    return false;
                }
                //发送avg指令
                var result = AGVTest(instruct, out errMsg);
                if (!result)
                {
                    errMsg = "avg返回结果：" + errMsg;
                    return false;
                }

                errMsg = "提交成功，" + cellName;
                trans.Complete();
                return true;
            }
            catch (Exception ex)
            {
                errMsg = "错误信息：" + ex.Message;
                trans.Dispose();
                return false;
                throw;
            }
        }

        /// <summary>
        /// 大件组垛
        /// </summary>
        /// <param name="errMsg"></param>
        /// <param name="stackingStorageDTO"></param>
        /// <returns></returns>

        public bool LargeStackingStorage(out string errMsg, LargeStackingStorageDTO largeStackingStorageDTO)
        {
            errMsg = string.Empty;
            string cellName = string.Empty;
            if (largeStackingStorageDTO.sampleCodes.Count == 0 || largeStackingStorageDTO.pallCode == null)
            {
                errMsg = "参数有误";
                return false;
            }
            using var trans = new TransactionScope();
            try
            {
                foreach (var sampleCode in largeStackingStorageDTO.sampleCodes)
                {
                    var receivingbilldteail = receivingbillDteailrepost.Get(s => s.MaterialCode == sampleCode && s.PositionType == 3);
                    if (receivingbilldteail is null)
                    {
                        errMsg = "未查出委托单或者样品不属于此库区";
                        trans.Dispose();
                        return false;
                    }
                    //根据委托单去查看是否有入库单号
                    var receorder = receivingOrderDetailrepost.Get(r => r.ReceivingBillId == receivingbilldteail.BillId);
                    TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                    if (receorder is null)
                    {
                        receivingOrder.OrderSn = "TW" + GetInOrderBarCode();
                    }
                    else
                    {
                        receivingOrder.OrderSn = receorder.OrderSn;
                    }

                    receivingOrder.BillType = 1;
                    receivingOrder.MaterialId = receivingbilldteail.MaterialId;
                    receivingOrder.MaterialCode = receivingbilldteail.MaterialCode;
                    receivingOrder.MaterialName = receivingbilldteail.MaterialName;
                    receivingOrder.Status = 3;
                    receivingOrder.ReceivingBillId = receivingbilldteail.BillId;
                    receivingOrder.ReceivingBillDetailId = receivingbilldteail.Id;
                    receivingOrder.CreateDate = DateTime.Now;
                    if (receivingOrderDetailrepost.Insert(receivingOrder) is null)
                    {
                        trans.Dispose();
                        errMsg = "添加入库单失败";
                        return false;
                    }
                    //查看箱号是否组垛过 没有组垛过就要从新生成一个组垛的号代表新的一次
                    var stacking = tStackingStorageServicerepost.Get(s =>
                    //s.OrderNo == receivingbilldteail.BillNo && 
                    s.PalletBarcode == largeStackingStorageDTO.pallCode
                    && s.Status == 1
                    );
                    TStackingStorage stackingStorage = new TStackingStorage();
                    if (stacking is null)
                    {
                        stackingStorage.Code = "ST" + GetInOrderBarCode();
                    }
                    else
                    {
                        stackingStorage.Code = stacking.Code;
                    }

                    stackingStorage.RelatedOrderDetailId = receivingOrder.Id;
                    stackingStorage.MaterialId = receivingbilldteail.MaterialId;
                    stackingStorage.MaterialCode = receivingbilldteail.MaterialCode;
                    stackingStorage.CreateDate = DateTime.Now;
                    stackingStorage.OrderNo = receivingbilldteail.BillNo;
                    stackingStorage.MaterialName = receivingbilldteail.MaterialName;
                    stackingStorage.Status = 1;
                    stackingStorage.PalletBarcode = largeStackingStorageDTO.pallCode; //箱号或托盘号
                    if (tStackingStorageServicerepost.Insert(stackingStorage) is null)
                    {
                        trans.Dispose();
                        errMsg = "组垛失败";
                        return false;
                    }
                }
                var IsOk = FullBoxLarge(largeStackingStorageDTO.pallCode, out cellName, out errMsg);
                if (IsOk)
                {
                    trans.Complete();
                    errMsg = "保存成功，上架仓位：" + cellName;
                    return true;
                }
                else
                {
                    trans.Dispose();
                    errMsg = "大件上架失败：" + errMsg;
                    return false;
                }
                   
            }
            catch (Exception ex)
            {
                trans.Dispose();
                errMsg = "大件上架失败" + ex.Message;
                return false;
                throw;
            }
        }

        /// <summary>
        /// 大件上架/或自动满箱（大件不用点满箱组垛完后直接上架）
        /// </summary>
        /// <param name="errMsg"></param>
        /// <param name="palletCode"></param>
        /// <returns></returns>
        private bool FullBoxLarge(string palletCode,out string cellName, out string errMsg)
        {
            errMsg = string.Empty;
            cellName = string.Empty;
            var stackingStorages = tStackingStorageServicerepost.GetList(s => s.Status == 1 && s.PalletBarcode == palletCode);
            if (stackingStorages.Count <= 0 || stackingStorages is null)
            {
                errMsg = "未查询到组垛信息";
                return false;
            }

            foreach (var storage in stackingStorages)
            {
                var orderdetail = receivingOrderDetailrepost.Get(r => r.Id == storage.RelatedOrderDetailId);
                if (orderdetail is null)
                {
                    errMsg = "未查询到组垛信息";
                    return false;
                }
                PalletBindMaterialModel palletBindMaterialModel = new PalletBindMaterialModel()
                {
                    PalletBarcode = storage.PalletBarcode,
                    StackingStorageId = storage.Id,
                    MaterialPackageBindModel = new MaterialPackageBindModel()
                    {
                        OrderDetailId = orderdetail.Id,
                        MaterialCode = storage.MaterialCode
                    }
                };
                var isok = NewExecCreateMaterialsInstruct(out errMsg,out cellName, orderdetail, palletBindMaterialModel);
                if (!isok)
                {
                    errMsg = "开始入库失败：" + errMsg;
                    return false;
                }
            }

            var instruct = instructrepost.Get(i => i.StackingStorageCode == stackingStorages[0].Code);
            if (instruct is null)
            {
                errMsg = "未查询到指令：" + errMsg;
                return false;
            }

            //发送avg指令
            var result = AGVTest(instruct, out errMsg);
            if (!result)
            {
                errMsg = "avg返回结果：" + errMsg;
                return false;
            }

            errMsg = "提交成功，" + cellName;
            return true;
        }

        /// <summary>
        /// 开始入库新
        /// </summary>
        /// <param name="errorMsg"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool NewExecCreateMaterialsInstruct(out string errorMsg, out string cellName,params object[] data)
        {
            errorMsg = "";
            cellName = string.Empty;
            if (data == null || data.Length < 2)
            {
                errorMsg = "参数错误";
                return false;
            }
            lock (_lockObj)
            {
                try
                {
                    TReceivingOrderDetail orderDetail = data[0] as TReceivingOrderDetail;
                    PalletBindMaterialModel palletBind = data[1] as PalletBindMaterialModel;
                    if (orderDetail == null || palletBind == null)
                    {
                        errorMsg = "参数错误";
                        return false;
                    }
                    TInstruct instruct = null;
                    //更新收货单明细表的组垛数量、保存垛主表信息、修改垛明细表的垛主表主键id
                    string palletBarcode = palletBind.PalletBarcode;
                    int cellId;
                    TCell allocateCell = null;
                    decimal? materialNum = 0;
                    decimal? price = 0;
                    bool result = false;
                    TPallet pallet = null;

                    #region 校验入库单

                    if (orderDetail.Status == 0)
                    {
                        errorMsg = "入库单未启动";
                        return false;
                    }
                    if (orderDetail.Status == 4 || orderDetail.Status == 5)
                    {
                        errorMsg = "入库单已完成";
                        return false;
                    }
                    if (orderDetail.Status != 3)
                    {
                        errorMsg = "当前入库单未执行";
                        return false;
                    }
                    if (orderDetail.Price.HasValue)
                    {
                        price = orderDetail.Price;
                    }

                    #endregion

                    pallet = palletrepost.Get(p => p.PalletBarcode == palletBind.PalletBarcode);
                    if (pallet == null)
                    {
                        errorMsg = "该托盘未维护";
                        return false;
                    }
                    if (pallet.Status == 0)
                    {
                        errorMsg = "该托盘已被禁用";
                        return false;
                    }

                    var stackingstorage = tStackingStorageServicerepost.Get(x => x.Id == palletBind.StackingStorageId);
                    if (stackingstorage is null)
                    {
                        errorMsg = "未查询到组垛信息";
                        return false;
                    }
                    stackingstorage.Status = 2;
                    if (!tStackingStorageServicerepost.Update(stackingstorage))
                    {
                        errorMsg = "修改组垛数据失败！";
                        return false;
                    }


                    //cellId = allocateCell.Id;
                    decimal? putawayQTY = putawayorderrepost.GetList(p => p.SourceType == 1 && p.RelatedOrderDetailId == orderDetail.Id).Sum(t => t.Qty).GetValueOrDefault();

                    //最小库存单位
                    //materialNum = palletBind.MaterialPackageBindModel.Qty;

                    bool hasSkuDetail = true;
                    //var stackingStorage = tStackingStorageServicerepost.Get(s => s.PalletBarcode == palletBarcode && s.MaterialCode == orderDetail.MaterialCode && s.RelatedOrderDetailId == orderDetail.Id);

                    var receivingOrderDetail = receivingOrderDetailrepost.Get(x => x.Id == orderDetail.Id);

                    var inst = instructrepost.Get(i => i.StackingStorageCode == stackingstorage.Code && i.Status ==2);
                    //生成wms指令
                    if (inst == null)
                    {
                        //寻找仓位还没有加条件
                        allocateCell = AllotCell(palletBind.PalletBarcode);
                        if (allocateCell is null)
                        {
                            errorMsg = "无可仓位，等一下再试试";
                            return false;
                        }
                        var cell = cellrepost.Get(c => c.Id == allocateCell.Id);
                        if (cell is null)
                        {
                            errorMsg = "更新仓位信息时未查询到仓位";
                            return false;
                        }
                        cell.BusinessType = EmBusinessType.In;
                        cell.IsLock = true;
                        cell.FullStatus = 1;
                        cell.Status = 2;
                        cell.ModifyDate = DateTime.Now;
                        if (!cellrepost.Update(cell))
                        {
                            errorMsg = "更新仓位货位信息失败";
                            return false;
                        }
                        
                        //确定avg的起点位置
                        string FromLocation;
                        if (pallet.Type == 0)
                        {
                            FromLocation = "O00001";
                        }
                        else
                        {
                            var oldcell = cellrepost.Get(c => c.Code == pallet.LocationCode);
                            oldcell.BusinessType = 0;
                            oldcell.IsLock = false;
                            oldcell.FullStatus = 0;
                            oldcell.Status = 1;
                            oldcell.ModifyDate = DateTime.Now;
                            if (!cellrepost.Update(oldcell))
                            {
                                errorMsg = "更新仓位货位信息失败";
                                return false;
                            }
                            FromLocation = pallet.ErplocationName;
                        }

                        instruct = new TInstruct
                        {
                            //WarehouseCode = stackingstorage.WarehouseCode,
                            Status = 2,
                            ToLocation = "",
                            //StackingStorageId = stackingStorageId,//换成code
                            StackingStorageCode = stackingstorage.Code,
                            WorkDeviceType = EmWorkDeviceType.AGV,
                            InstructType = EmInstructType.In,
                            Action = EmDeviceAction.Transport,
                            //RelatedOrderDetailId = orderDetail.Id,//换成code
                            RelatedOrderDetailCode = orderDetail.OrderSn,
                            DeviceCode = "",
                            FromLocation = FromLocation, //avg的起点位置
                            ExpectedToLocation = allocateCell.Code, //分配储位的code
                            LogicalCellAddr = allocateCell.Erpcode,//分配储位的erpcode
                            InstructIndex = 1,
                            PalletBarcode = palletBarcode,
                            ScanedBarcode = palletBarcode,
                            Priority = 9999,
                            //Qty = materialNum.GetValueOrDefault(),
                            FinishedQty = 0,
                            StartTime = DateTime.Now,
                            BusinessGroupId = Guid.NewGuid(),
                            BusinessType = (int)EmBusinessType.In,
                            BillType = (int)orderDetail.BillType.GetValueOrDefault(),

                        };
                        if (instructrepost.Insert(instruct) is null)
                        {
                            errorMsg = "指令保存失败";
                            return false;
                        }
                        var pall = palletrepost.Get(p => p.Id == pallet.Id);
                        if (pall is null)
                        {
                            errorMsg = "更新托盘信息时未查询到托盘";
                            return false;
                        }
                        pall.LocationCode = "";
                        pall.LocationName = "";
                        pall.ErplocationName = "";
                        if (!palletrepost.Update(pall))
                        {
                            errorMsg = "更新托盘货位信息失败";
                            return false;
                        }
                    }
                    else
                    {
                        allocateCell = cellrepost.Get(c => c.Erpcode == inst.LogicalCellAddr);
                        if (allocateCell is null)
                        {
                            errorMsg = "分配仓位未查询到";
                            return false;
                        }
                    }

                    //修改组垛表的预留仓位信息
                    stackingstorage.ExpectedLocation = allocateCell.Code;
                    if (!tStackingStorageServicerepost.Update(stackingstorage))
                    {
                        errorMsg = "分配的收货仓位失败";
                        return false;
                    }

                    //保存库存
                    TInventory inventory = new TInventory()
                    {
                        //WarehouseId = stackingstorage.WarehouseId,
                        WarehouseCode = allocateCell.WhCode,
                        WarehouseName = allocateCell.WhName,
                        AreaCode = allocateCell.AreaCode,
                        AreaName = allocateCell.AreaName,
                        //CompanyId = order.CompanyId,
                        //CompanyName = order.CompanyName,
                        LocationId = allocateCell.Id,
                        LocationCode = allocateCell.Code,
                        //LocationDepth = allocateCell.DepthIndex,
                        LocationName = allocateCell.Name,
                        Status = 3,
                        //TaskId = instructs[0].TaskId,
                        PalletBarcode = palletBarcode,
                        ParentPalletBarcode = stackingstorage.ParentPalletBarcode,
                        //RelatedOrderId = orderDetail.OrderId,
                        RelatedOrderDetailId = orderDetail.Id,
                        BillType = (int)orderDetail.BillType.GetValueOrDefault(),
                        IsLock = true,
                        CreateDate = DateTime.Now,
                        MaterialId = orderDetail.MaterialId,
                        MaterialCode = orderDetail.MaterialCode,
                        MaterialName = orderDetail.MaterialName,
                        HasSkuDetail = hasSkuDetail,
                        PutawayQty = materialNum,
                        UnitId = orderDetail.UnitId,
                        UnitName = orderDetail.UnitName,
                        MaterialKeyId = orderDetail.MaterialKeyId,
                        BatchNo = orderDetail.BatchNo,
                        OwnerId = orderDetail.OwnerId,
                        OwnerName = orderDetail.OwnerName,
                        ExpireDate = orderDetail.ExpireDate,
                        ProductDate = orderDetail.ProductDate,
                        SupplierId = orderDetail.SupplierId,
                        SupplierName = orderDetail.SupplierName,
                        MaterialTypeCode = orderDetail.MaterialTypeCode,
                        MaterialTypeName = orderDetail.MaterialTypeName,
                        PickedQty = 0,
                        //PackQty = packageBarcodes.Count,
                        ErplocationCode = allocateCell.Erpcode,
                        RoutewayId = allocateCell.RoutewayId,
                        StackingStorageId = stackingstorage.Id,
                        //LocationHeightType = allocateCell.HeightType,
                        //RealHeightType = heightType,
                        LogicalPartCode = orderDetail.LogicalPartCode,//按单据来
                        LocationColumnNo = allocateCell.ColumnNo,
                        LocationLayerNo = allocateCell.LayerNo,
                        LocationDistanceValue = allocateCell.DistanceValue,
                        LocationLineNo = allocateCell.LineNo,
                        DeptCode = orderDetail.DeptCode,
                        DeptName = orderDetail.DeptName,
                        TotalPrice = price * materialNum,
                        Price = price,
                        AvailableQty = palletBind.MaterialPackageBindModel.Qty,
                        AllocateQty = 0
                    };

                    if (inventoryrepost.Insert(inventory) is null)
                    {
                        errorMsg = "库存主表保存失败";
                        return false;
                    }
                    //保存上架单主表
                    Random random = new Random(Guid.NewGuid().GetHashCode());
                    int randNum = random.Next(1, 10000);
                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff") + randNum.ToString("0000");
                    string putawayCode = "PUT" + str;
                    TPutawayOrder putawayOrder = new TPutawayOrder()
                    {
                        Code = putawayCode,
                        RelatedOrderDetailId = orderDetail.Id,
                        StackingStorageId = stackingstorage.Id,
                        PalletBarcode = palletBarcode,
                        ParentPalletBarcode = stackingstorage.ParentPalletBarcode,
                        LocationCode = stackingstorage.ExpectedLocation,
                        //LocationDepth = allocateCell.DepthIndex==0?null : allocateCell.DepthIndex,
                        Status = 4,
                        Qty = materialNum,
                        CreateDate = DateTime.Now,
                        MaterialId = orderDetail.MaterialId,
                        MaterialCode = orderDetail.MaterialCode,
                        MaterialName = orderDetail.MaterialName,
                        MaterialKeyId = orderDetail.MaterialKeyId,
                        BatchNo = orderDetail.BatchNo,
                        OwnerId = orderDetail.OwnerId,
                        OwnerName = orderDetail.OwnerName,
                        CreateUserId = 0,
                        CreateUserName = "系统",
                        SourceType = 1,
                    };

                    if (putawayorderrepost.Insert(putawayOrder) is null)
                    {
                        errorMsg = "上架单主表保存失败";
                        return false;
                    }

                    //库存明细保存
                    TInventoryDetail inventoryDetail = new TInventoryDetail()
                    {
                        InventoryId = inventory.Id,
                        Barcode = "",
                        PackageBarcode = palletBarcode,// package.PackageBarcode
                        PalletBarcode = palletBarcode,
                        CreateDate = DateTime.Now,
                        SkuNum = materialNum,
                        IsSku = false,
                        Price = price,
                        TotalPrice = price * materialNum
                    };

                    if (inventorydetailrepost.Insert(inventoryDetail) is null)
                    {
                        errorMsg = "库存明细表保存失败";
                        return false;
                    }
                    //上架单明细表保存
                    TPutawayOrderDetail putawayOrderDetail = new TPutawayOrderDetail()
                    {
                        PutawayOrderId = putawayOrder.Id,
                        PalletBarcode = palletBarcode,
                        PackageBarcode = palletBarcode,//package.PackageBarcode
                        MaterialBarcode = "",
                    };

                    if (putawayorderdetailrepost.Insert(putawayOrderDetail) is null)
                    {
                        errorMsg = "上架单明细表保存失败";
                        return false;
                    }
                    cellName = "储位地址：" + allocateCell.Name;
                    return true;
                }
                catch (Exception ex)
                {
                    errorMsg = "入库失败：" + ex.Message;
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// 完成入库新
        /// </summary>
        /// <param name="instruct"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool NewExecInstructFinishedMaterials(TInstruct instruct, out string errorMsg)
        {
            errorMsg = "";
            if (string.IsNullOrEmpty(instruct.PalletBarcode))
            {
                errorMsg = "参数错误";
                return false;
            }
            lock (_lockObj)
            {
                using var trans = new TransactionScope();
                try
                {
                    List<SamplePutawayModel> samplePutawayModels = new List<SamplePutawayModel>();
                    var stackings = tStackingStorageServicerepost.GetList(s => s.Code == instruct.StackingStorageCode);
                    if (stackings is null || stackings.Count <= 0)
                    {
                        errorMsg = "组垛信息不存在";
                        trans.Dispose();
                        return false;
                    }

                    foreach (var stacking in stackings)
                    {
                        var orderDetail = receivingOrderDetailrepost.Get(r => r.Id == stacking.RelatedOrderDetailId);
                        if (orderDetail is null)
                        {
                            errorMsg = "入库单明细不存在";
                            trans.Dispose();
                            return false;
                        }
                        var inventory = inventoryrepost.Get(i => i.RelatedOrderDetailId == orderDetail.Id && i.LocationCode == instruct.ExpectedToLocation && i.PalletBarcode == instruct.PalletBarcode && i.Status == 3);
                        if (inventory == null)
                        {
                            errorMsg = "库存数据不存在";
                            trans.Dispose();
                            return false;
                        }
                        List<TInventoryDetail> inventoryDetailList = inventorydetailrepost.GetList(i => i.InventoryId == inventory.Id).ToList();
                        if (inventoryDetailList == null || inventoryDetailList.Count == 0)
                        {
                            errorMsg = "库存明细数据不存在";
                            trans.Dispose();
                            return false;
                        }

                        DateTime? now = DateTime.Now;
                        var putawayOrder = putawayorderrepost.Get(p => p.Status == 4 && p.RelatedOrderDetailId == orderDetail.Id && p.StackingStorageId == stacking.Id);
                        putawayOrder.Status = 5;
                        putawayOrder.Fifodate = now;
                        if (!putawayorderrepost.Update(putawayOrder))
                        {
                            errorMsg = "上架单状态修改失败";
                            trans.Dispose();
                            return false;
                        }
                        var inventory1 = inventoryrepost.Get(i => i.Id == inventory.Id);
                        inventory1.Status = 1;
                        inventory1.AllocateQty = instruct.Qty;
                        inventory1.InStockDate = now;
                        inventory1.InStockShortDate = Convert.ToInt32(now.Value.ToString("yyyyMMdd"));
                        inventory1.PutawayQty = instruct.Qty;
                        inventory1.IsLock = false;

                        if (!inventoryrepost.Update(inventory1))
                        {
                            errorMsg = "库存状态修改失败";
                            trans.Dispose();
                            return false;
                        }

                        //修改仓位的状态和信息
                        var cell1 = cellrepost.Get(c => c.Id == inventory.LocationId);
                        cell1.IsLock = false;
                        cell1.BusinessType = 0;
                        cell1.Status = 1;
                        cell1.ModifyDate = now;

                        if (!cellrepost.Update(cell1))
                        {
                            errorMsg = "仓位状态修改失败";
                            trans.Dispose();
                            return false;
                        }

                        //修改托盘的状态和信息
                        var pall = palletrepost.Get(p => p.PalletBarcode == inventory.PalletBarcode);
                        if (pall is null)
                        {
                            errorMsg = "未查询到箱号或托盘信息";
                            trans.Dispose();
                            return false;
                        }
                        pall.LocationCode = cell1.Code;
                        pall.LocationName = cell1.Name;
                        pall.ErplocationName = cell1.Erpcode;

                        if (!palletrepost.Update(pall))
                        {
                            errorMsg = "修改箱号或托盘所在仓位错误";
                            trans.Dispose();
                            return false;
                        }

                        var receivingOrderDetail = receivingOrderDetailrepost.Get(r => r.Id == orderDetail.Id);
                        //receivingOrderDetail.ReceivedQty = modifyOrderDetail.ReceivedQty;
                        receivingOrderDetail.InStarDate = orderDetail.InStarDate == null ? now : orderDetail.InStarDate;
                        receivingOrderDetail.Status = 4;

                        if (!receivingOrderDetailrepost.Update(receivingOrderDetail))
                        {
                            errorMsg = "订单明细修改失败";
                            trans.Dispose();
                            return false;
                        }
                        instruct.Status = 4;
                        if (!instructrepost.Update(instruct))
                        {
                            errorMsg = "修改指令失败";
                            trans.Dispose();
                            return false;
                        }
                        //保存库存日志表
                        TInventoryLog inventoryLog = new TInventoryLog()
                        {
                            SourceType = 0,
                            SourceSn = orderDetail.OrderSn,
                            WarehouseId = orderDetail.WarehouseId,
                            WarehouseName = orderDetail.WarehouseName,
                            AreaName = inventory.AreaName,
                            AreaId = inventory.AreaId,
                            LocationCode = inventory.LocationCode,
                            PalletBarcode = instruct.PalletBarcode,
                            OwnerId = orderDetail.OwnerId,
                            OwnerName = orderDetail.OwnerName,
                            MaterialId = orderDetail.MaterialId,
                            MaterialCode = orderDetail.MaterialCode,
                            MaterialName = orderDetail.MaterialName,
                            BatchNo = orderDetail.BatchNo,
                            StartQty = 0,
                            ChangeQty = instruct.Qty,
                            EndQty = instruct.Qty,
                            BaseUnitId = orderDetail.UnitId,
                            BaseUnitName = orderDetail.UnitName,
                            CreateDate = DateTime.Now,
                        };
                        if (inventorylogrepost.Insert(inventoryLog) is null)
                        {
                            errorMsg = "库存日志表保存失败";
                            trans.Dispose();
                            return false;
                        }

                        //获取样品节点 生成回传样品数据
                        var receivingobj = receivingbillDteailrepost.Get(r=>r.MaterialCode == stacking.MaterialCode);
                        if (receivingobj is null)
                        {
                            errorMsg = "获取样品节点失败";
                            trans.Dispose();
                            return false;
                        }
                        if (receivingobj.PositionType is null)
                        {
                            errorMsg = "获取样品节点失败";
                            trans.Dispose();
                            return false;
                        }
                        var nodename = SwitchLimsNodeName(receivingobj.PositionType.GetValueOrDefault());
                        samplePutawayModels.Add(new SamplePutawayModel() //添加样品节点信息
                        {
                            nodeName = nodename,
                            positionType = receivingobj.PositionType.ToString(),
                            sampleId = receivingobj.MaterialId.GetValueOrDefault()

                        });
                    }

                    //回传lims 样品上架
                    var limsres = limsService.SamplePutaway(samplePutawayModels);
                    if (limsres.code != 200)
                    {
                        receivingservicelogger.LogError("回传lims样品上架信息失败 ,入参：" + samplePutawayModels.ToJson() + "出参" + limsres.ToJson());
                        errorMsg = "回传lims样品上架失败：" + limsres.msg;
                        trans.Dispose();
                        return false;
                    }
                    receivingservicelogger.LogInformation("回传lims样品上架信息成功 ,入参：" + samplePutawayModels.ToJson() + "出参" + limsres.ToJson());
                    trans.Complete();
                    errorMsg = "保存成功";
                    return true;

                }
                catch (Exception ex)
                {
                    errorMsg = "入库失败:" + ex.Message;
                    trans.Dispose();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// avg走出储位后熄灭电子标签
        /// </summary>
        public bool OutElectronicTags(TInstruct instruct, out string errorMsg)
        {
            if (string.IsNullOrEmpty(instruct.PalletBarcode))
            {
                errorMsg = "参数错误";
                return false;
            }
            var stackings = tStackingStorageServicerepost.GetList(s => s.Code == instruct.StackingStorageCode);
            if (stackings is null || stackings.Count <= 0)
            {
                errorMsg = "组垛信息不存在";
                return false;
            }
            SuccessTagRequest successTagRequest = new SuccessTagRequest();
            successTagRequest.nWall = stackings[0].NWall;
            successTagRequest.seqNum = stackings[0].SeqNum;
            successTagRequest.tagList = new List<Tag>()
            {
                new Tag() { showColor = 5, showData = "0", tagIndex = stackings[0].TagIndex },
            };
            //调用电子标签点亮地址
            var IsLis = electronicTSpreadWallsags.successTagResults(successTagRequest, out errorMsg);
            if (!IsLis)
            {
                errorMsg = "点亮电子标签地址失败：" + errorMsg;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 查询样品所在分播墙位置
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <param name="OutMsg"></param>
        /// <returns></returns>
        public bool SelectElectronicTagsSample(string sampleCode, out string OutMsg)
        {
            OutMsg = string.Empty;
            if (string.IsNullOrEmpty(sampleCode))
            {
                OutMsg = "参数错误";
                return false;
            }
            var stacking = tStackingStorageServicerepost.Get(s=>s.MaterialCode == sampleCode && s.Status == 1);
            if (stacking == null)
            {
                OutMsg = "未查询到样品组垛信息，" + sampleCode;
                return false;
            }
            SuccessTagRequest successTagRequest = new SuccessTagRequest();
            successTagRequest.nWall = stacking.NWall;
            successTagRequest.seqNum = stacking.SeqNum;
            successTagRequest.tagList = new List<Tag>()
            {
                new Tag() { showColor = 6, showData = stacking.TagIndex, tagIndex = stacking.TagIndex },
            };
            //点亮多个地址是可会出错所有需要回滚
            using var trans = new TransactionScope();
            try
            {
                //调用电子标签点亮地址
                var IsLis = electronicTSpreadWallsags.successTagResults(successTagRequest, out OutMsg);
                if (!IsLis)
                {
                    OutMsg = "点亮电子标签地址失败：" + OutMsg;
                    trans.Dispose();
                    return false;
                }

                OutMsg = "查询成功：箱号为，" + stacking.PalletBarcode;
                trans.Complete();
                return true;
            }
            catch (Exception ex)
            {
                OutMsg = "查询失败，" + ex.Message;
                trans.Dispose();
                return false;
                throw;
            }
            

        }

        /// <summary>
        /// 分播墙上架解绑样品
        /// </summary>
        /// <returns></returns>
        public bool InUnbindingBoxSample(string pallCode, string sampleCode, out string OutMsg)
        {
            OutMsg = string.Empty;
            using var trans = new TransactionScope();
            try
            {
                var pall = palletrepost.Get(p => p.PalletBarcode == pallCode && p.Status == 1);
                if (pall == null)
                {
                    OutMsg = pallCode + "箱子不存在或已被禁用！";
                    return false;
                }

                //查询委托单样品信息
                var receivingbilldteail = receivingbillDteailrepost.Get(s => s.MaterialCode == sampleCode && s.PositionType == 1);
                if (receivingbilldteail is null)
                {
                    OutMsg = "未查出委托单或者样品不属于此库区，" + sampleCode;
                    return false;
                }

                // 查询出组垛的数据
                var stacking = tStackingStorageServicerepost.Get(s => s.Status == 1 && s.PalletBarcode == pallCode && s.MaterialCode == sampleCode);
                if (stacking == null)
                {
                    OutMsg = "没有查到样品组垛的记录，" + sampleCode;
                    return false;
                }

                var orderdeilte = receivingOrderDetailrepost.Get(o => o.Id == stacking.RelatedOrderDetailId);
                if (orderdeilte == null)
                {
                    OutMsg = "没有查到样品的记录，" + sampleCode;
                    return false;
                }

                //删除组垛数据
                if (!tStackingStorageServicerepost.Delete(stacking))
                {
                    OutMsg = "样品解绑失败，" + sampleCode;
                    trans.Dispose();
                    return false;
                }

                if (!receivingOrderDetailrepost.Delete(orderdeilte))
                {
                    OutMsg = "样品解绑失败，" + sampleCode;
                    trans.Dispose();
                    return false;
                }

                //查询箱子中是否还要样品如果没有需要修改箱子的所在的仓位信息
                var stackingstorages = tStackingStorageServicerepost.GetList(s => s.Status == 1 && s.PalletBarcode == pallCode && s.SeqNum != null && s.NWall != null && s.TagIndex != null);
               
                if (stackingstorages.Count() == 0)
                {
                    //查询需要修改的仓位
                    var cellobj = cellrepost.Get(c => c.Code == pall.LocationCode);
                    cellobj.BusinessType = EmBusinessType.None;
                    cellobj.IsLock = false;
                    cellobj.Status = 8;
                    if (!cellrepost.Update(cellobj))
                    {
                        OutMsg = "分播墙仓位状态修改失败，" + cellobj.Name;
                        trans.Dispose();
                        return false;
                    }
                }
                OutMsg = "解绑成功";
                trans.Complete();
                return true;
            }
            catch (Exception ex)
            {
                OutMsg = ex.Message;
                trans.Dispose();
                return false;
                throw;
            }
        }

        #region 调用方法
        /// <summary>
        /// 分配仓位
        /// </summary>
        /// <param name="palletBarcode"></param>
        /// <returns></returns>
        public TCell? AllotCell(string palletBarcode)
        {
            TCell allotCell = null; //先写死一个储位因为货架上有的储位是有箱子的仓位表里面不知道
           var pall = palletrepost.Get(p=>p.PalletBarcode == palletBarcode);
            if (pall is null)
            {
                return null;
            }
            //var cellList = cellrepost.GetList(c=>c.Status == 1 && c.FullStatus == 0 && c.IsLock == false && c.LogicalPartCode == pall.LogicalPartCode); //以前分配储位的条件
            string configLogicalPartCode;
            List<string> configLineNo;
            List<string> configLayerNo;
            List<TCell> cellList;
            if (pall.Type !=0)
            {
                //急用分配储位的条件
                configLogicalPartCode = _config.GetSection("LogicalPartCode").Value;
                configLineNo = _config.GetSection("LineNo").Value.Split(',').ToList();
                configLayerNo = _config.GetSection("LayerNo").Value.Split(',').ToList();
                cellList = cellrepost.GetList(c => c.Status == 1 && c.FullStatus == 0 && c.IsLock == false && c.LogicalPartCode == configLogicalPartCode && configLineNo.Contains(c.LineNo.ToString()) && configLayerNo.Contains(c.LayerNo.ToString()));
            }
            else
            {
                configLogicalPartCode = pall.PalletBarcode;
                cellList = cellList = cellrepost.GetList(c => c.Status == 1 && c.FullStatus == 0 && c.IsLock == false && c.LogicalPartCode == pall.LogicalPartCode);
            }

            if (cellList is null || cellList.Count <= 0)
            {
                return null;
            }

            //这里应该还需要加一个条件 ：查看仓位是否具备可以放箱子的条件 因为有的储位有可能存在空箱
            foreach (var cell in cellList)
            {
                var data = palletrepost.Get(p=>p.LocationCode == cell.Code);
                if (data != null)
                {
                    continue;
                }
                return allotCell = cell;
            }
            return null;
           
        }

        /// <summary>
        /// 调用avg
        /// </summary>
        /// <param name="instruct"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private bool AGVTest(TInstruct instruct, out string errMsg)
        {
            errMsg = string.Empty;
            if (instruct == null)
            {
                errMsg = "指令为空！";
                return false;
            }
            var pall = palletrepost.Get(p => p.PalletBarcode == instruct.PalletBarcode);
            if (pall is null)
            {
                errMsg = "未查询出箱号和托盘！" + instruct.PalletBarcode;
                return false;
            }
            if (pall.Type == null)
            {
                errMsg = "托盘类型为空！";
                return false;
            }
            (string avgPalletType, string avgTaskType) = SwitchType(pall.Type.GetValueOrDefault());
            if (string.IsNullOrEmpty(avgPalletType))
            {
                errMsg = "转换AGV容器类型失败";
                return false;
            }
            //return true;
            //绑定
            BindCtnrAndBinModel bindCtnrAndBinModel = new BindCtnrAndBinModel();

            var uuid = Guid.NewGuid();
            bindCtnrAndBinModel.reqCode = uuid.ToString("N");
            bindCtnrAndBinModel.taskCode = bindCtnrAndBinModel.reqCode;
            bindCtnrAndBinModel.reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //绑定用户
            bindCtnrAndBinModel.clientCode = "PDA";
            //绑定容器类型 大容器类型
            bindCtnrAndBinModel.ctnrTyp = avgPalletType;
            //banging起始目标储位  
            bindCtnrAndBinModel.stgBinCode = instruct.FromLocation;
            //绑定
            bindCtnrAndBinModel.indBind = "1";

            var res = aGVService.BindCntrAndUnBindTask(bindCtnrAndBinModel);
            if (res.code != "0")
            {
                errMsg = "AVG绑定失败：" + res.message;
                return false;
            }


            //添加任务单
            AddTaskModel addTaskModel = new AddTaskModel();
            addTaskModel.reqCode = Guid.NewGuid().ToString("N");
            addTaskModel.clientCode = "PDA";
            //ARM入库出库
            addTaskModel.TaskTyp = avgTaskType;

            
            //叉车对应的大容器类型
            addTaskModel.CtnrTyp = avgPalletType;
            addTaskModel.taskCode = instruct.BusinessGroupId.ToString();

            //任务起始点仓位编码
            addTaskModel.PositionCodePath = new PositionCodePathDto[2] {
                    new PositionCodePathDto() {
                        //叉车实际位置
                        PositionCode=instruct.FromLocation,// 起始地址 D00080A2502013
                        Type="05"//固定05
                    },
                    //实际传入编号，测试传入仓位
                    new PositionCodePathDto() {
                        PositionCode=instruct.LogicalCellAddr,//ERP目标地址
                        Type="05"
                    }
                };

            var res2 = aGVService.CreateTask(addTaskModel);
            if (res2.code != "0")
            {
                errMsg = "AVG：" + res2.message;
                return false;
            }
            errMsg = errMsg;
            return true;

        }

        /// <summary>
        /// 把WMS的容器类型转换为AGV的容器类型
        /// </summary>
        /// <param name="wmsType"></param>
        /// <returns></returns>
        private (string, string) SwitchType(int wmsType)
        {
            switch (wmsType)
            {
                case 0:
                    return ("3", "B1");
                case 1:
                    return ("2", "A11");
                case 2:
                    return ("1", "A10");
                default:
                    return (null, null);
            }
        }

        /// <summary>
        /// 获取回传lims节点名称
        /// </summary>
        /// <param name="positionType"></param>
        /// <returns></returns>
        private string? SwitchLimsNodeName(int positionType)
        {
            switch (positionType)
            {
                case 1:
                    return "智慧仓储-货架";
                case 2:
                    return "智慧仓储-快递柜";
                case 3:
                    return "智慧仓储-托盘区";
                default:
                    return null;
            }
        }
        #endregion
    }
}
